//
//  JZHPublishActivityViewController.m
//  极致荟
//
//  Created by mac on 14-4-21.
//  Copyright (c) 2014年 mac. All rights reserved.
//

#import "JZHPublishActivityViewController.h"
#import "JZHImageView.h"
#import "SuperUIScrollView.h"
#import "JZHActivities.h"
#import "JZHContactsViewController.h"
@interface JZHPublishActivityViewController ()
{
    BOOL keytype;//YES选择人数  NO选择日期
    NSDateComponents *comps;
    NSUInteger unitFlags;
    NSCalendar *calendar;
    NSDate *date;//
    NSDate *okdate;
    JZHActivities *act;
    NSMutableArray *farr;//邀请好友列表
    NSString *selectImage;//选择的图片地址
    NSDictionary *datadic;
   // int rnumber;//参与人数
}
@property (nonatomic,strong) NSMutableArray *userlist;//通讯录选择结果
@property (weak, nonatomic) IBOutlet SuperUIScrollView *conentScroller;
@property (weak, nonatomic) IBOutlet UISwitch *timeon;
@property (strong, nonatomic) IBOutlet UIPickerView *pickerr;
@property (strong, nonatomic) IBOutlet UIPickerView *picker;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmeType;
@property (strong, nonatomic) IBOutlet UIView *pickerview;
@property (weak, nonatomic) IBOutlet UITextField *didian;
@property (weak, nonatomic) IBOutlet UIButton *endbut;
@property (weak, nonatomic) IBOutlet UITextView *content;

@property (weak, nonatomic) IBOutlet UITextField *titletext;
@property (weak, nonatomic) IBOutlet UISegmentedControl *FYsegmet;

@end

@implementation JZHPublishActivityViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (JZHPublishActivityViewController *)inittype:(int)acttype
{
    JZHPublishActivityViewController *jzh=[[JZHPublishActivityViewController alloc]init];
    jzh.tyeps=[NSNumber numberWithInt:acttype];
    return jzh;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"%d",self.userlist.count);
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    farr=[[NSMutableArray alloc] init];
    
    act=[[JZHActivities alloc] init];
    self.userlist=[[NSMutableArray alloc] init];
    [self.conentScroller TapGestureEnend:YES];
    [self postImages];
    //时间数据管理类初始化
    calendar=[NSCalendar currentCalendar];
    unitFlags = NSYearCalendarUnit| NSMonthCalendarUnit |NSCalendarUnitMonth | NSDayCalendarUnit |NSHourCalendarUnit |NSMinuteCalendarUnit |NSWeekdayCalendarUnit|NSWeekOfMonthCalendarUnit;
    comps = [calendar components:unitFlags fromDate:[NSDate date]];
    [comps setMinute:0];
    [comps setHour:0];
    NSDateFormatter *form=[[NSDateFormatter alloc]init];
    [form setDateFormat:@"yyyy年MM月dd日"];
    date=[calendar dateFromComponents:comps];
    self.datelable.text=[form stringFromDate:date];

    // Do any additional setup after loading the view from its nib.
    self.conentScroller.contentSize = CGSizeMake(320, 640);
    self.navigationItem.title=@"新活动";
    //设置左侧按钮
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 12, 20)];
    [leftButton addTarget:self action:@selector(leftDrawerButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    [self.timeon setFrame:CGRectMake(self.timeon.frame.origin.x, self.timeon.frame.origin.y, 60, 30)];
    if(OSVersionIsAtLeastiOS7>=7.0)
    {
        self.automaticallyAdjustsScrollViewInsets=NO;
    }
    
    [self.pickerview setFrame:self.view.frame];
  
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 5)];
    [rightButton addTarget:self action:@selector(rightDrawerButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.datetext setInputView:self.pickercon];
    [rightButton setFrame:CGRectMake(0, 0, 50, 10)];
    [rightButton setTitle:@"发布" forState:UIControlStateNormal];
    [rightButton setTitleColor:TEXTBULE forState:UIControlStateNormal];
    [rightButton setFont:[UIFont systemFontOfSize:18]];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButton;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keynot:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
}

/// 上传数据准备
- (void)posthttp
{
    
    [MMProgressHUD showWithStatus:@"发布中..."];
        long long int times=[okdate timeIntervalSince1970];
        NSLog(@"%@",[User defuceUser].citydic);
        //去除前后空格
        NSString *tiltestr=[self.titletext.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:tiltestr,@"subject",
                           [NSNumber numberWithInt:9 ],@"cityId",
                           [NSNumber numberWithInt:[User defuceUser].userId],@"userId",
                           self.content.text,@"detail",
                           self.didian.text,@"address",
                           [NSNumber numberWithInt:[self.FYsegmet selectedSegmentIndex]],@"payment",
                           [NSNumber numberWithLongLong:times],@"partyTime",selectImage,@"image",
                            [NSNumber numberWithInt:[self.segmeType selectedSegmentIndex]],@"partyType",
                           self.tyeps,@"partyCate", nil];
    [HttpRequest httpRequestPost:JZHHTTPURL(@"party/addParty") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
            if(rerurncode==0)
            {
                NSLog(@"%@",data);
                [MMProgressHUD showSuccessWithTips:@"发布成功"];
                [UINavigationController Pop:self];
            }else
            {
                [MMProgressHUD dismissWithError:@"发布失败"];
            }
         }];

}
- (void)leftDrawerButtonPress:(UIButton *)but
{
    [UINavigationController Pop:self];
}

///请求该类型下的系统规定图片
- (void)postImages
{
    NSDictionary *dic=[[NSDictionary alloc] initWithObjectsAndKeys:self.tyeps,@"cateCode", nil];
    [HttpRequest httpRequestPost:JZHHTTPURL(@"party/getCateImgList") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
        if(rerurncode==0)
        {
            NSLog(@"%@",data);
            datadic=[[NSDictionary alloc] init];
            datadic=[data objectForKey:@"data"];
            [self addpartimage:[[data objectForKey:@"data"] objectForKey:@"list"] imageheadr:[[data objectForKey:@"data"] objectForKey:@"imgPrefix"]];
        }
    }];
}

- (void)addpartimage:(NSArray *)arr imageheadr:(NSString *)path
{
    int index=0;
    for(int i=0;i<2;i++)
    {
        for(int j=0;j<4;j++)
        {
            if(index>=arr.count)
            {
                return;
            }
            UIImageView *image=[[UIImageView alloc] initWithFrame:CGRectMake(j*70+(j*5), i*70+(i*5), 70, 70)];
            [ImageCache imageUrl:[path stringByAppendingString:arr[index]] UiImageview:image];
            image.tag=400+index;
            [image setUserInteractionEnabled:YES];
            [image addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectImage:)]];
            [image.layer setCornerRadius:3];
            [image.layer setMasksToBounds:YES];
            
            UIImageView *gou=[[UIImageView alloc] initWithFrame:CGRectMake(55, 0, 15, 15)];
            [gou setImage:[UIImage imageNamed:@"fgou"]];
            gou.tag=444;
            if(index==0)
            {
                selectImage=arr[0];
                [image.layer setBorderWidth:2];
                [image.layer setBorderColor:[[UIColor blueColor] CGColor]];
                gou.hidden=NO;
            }else
            {
                [image.layer setBorderWidth:1];
                [image.layer setBorderColor:[[UIColor grayColor] CGColor]];
                gou.hidden=YES;
            }
            
            [image addSubview:gou];
            [self.partyimageview addSubview:image];
            index++;
        }
        
    }
}

- (void)selectImage:(UITapGestureRecognizer *)tap
{
    UIImageView *sender=(UIImageView *)tap.view;
    for(UIImageView *image in [self.partyimageview subviews])
    {
        if(sender==image)
        {
            selectImage=[datadic objectForKey:@"list"][image.tag-400];
            [image viewWithTag:444].hidden=NO;
            [image.layer setBorderWidth:2];
            [image.layer setBorderColor:[[UIColor blueColor] CGColor]];
        }else
        {
            [image viewWithTag:444].hidden=YES;
            [image.layer setBorderWidth:1];
            [image.layer setBorderColor:[[UIColor grayColor] CGColor]];
        }
    }
}
- (void)rightDrawerButtonPress:(UIButton *)but
{
    
    //去除前后空格
    NSString *tiltestr=[self.titletext.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if(tiltestr.length<5)
    {
        [MMProgressHUD showInformationWithTips:@"标题长度不够"];
        return;
    }
    
    if(self.datetext.text.length<1)
    {
        [MMProgressHUD showInformationWithTips:@"请选择活动时间"];
        return;
    }
    
    
    if(self.didian.text.length<6)
    {
        [MMProgressHUD showInformationWithTips:@"请填写详细活动地点"];
        return;
    }
    
    if(self.content.text.length<10)
    {
        [MMProgressHUD showInformationWithTips:@"活动详情说明不少于10个字"];
        return;
    }
    
    [self posthttp];
}


- (IBAction)selectType:(UISegmentedControl *)sender {
    NSLog(@"%d",sender.selectedSegmentIndex)  ;
    if(sender.selectedSegmentIndex==1)
    {
        act.actBmType=1;
    }else
    {
       act.actBmType=0;
        [self.navigationController pushViewController:[[JZHContactsViewController alloc] initIsPusNote:nil farr:self.userlist] animated:YES];
        self.endbut.hidden=YES;
    }
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


///键盘通知
- (void)keynot:(NSNotification *)not
{
   // NSLog(@"%@",not);
    CGPoint bpoint=[[[not userInfo] objectForKey:UIKeyboardCenterBeginUserInfoKey] CGPointValue];
    CGPoint epoint=[[[not userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] CGPointValue];
    

    if([self.datetext isFirstResponder] || [self.didian isFirstResponder] || [self.content isFirstResponder] )
    {
        NSLog(@"b %f",self.view.center.y);
        if(self.view.center.y+(epoint.y-bpoint.y)/2<=self.view.frame.size.height/2)
        {
            [UIView animateWithDuration:0.3 animations:^{
                [self.view setCenter:CGPointMake(self.view.center.x, self.view.center.y+(epoint.y-bpoint.y)/2)];
                NSLog(@"e %f",self.view.center.y);
            }];
        }else
        {
            [UIView animateWithDuration:0.3 animations:^{
                [self.view setCenter:CGPointMake(self.view.center.x, self.view.frame.size.height/2)];
            }];

        }
        
    }

}
#pragma mark---UIPckerView---代理
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if(keytype)
    {
        return 1;
    }else
    {
        return 3;
    }
    
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if(keytype)
    {
        return 47;
    }else
    {
        switch (component)
        {
            case 0:
                return 60;
                break;
             case 1:
                return 24;
            default:
                return 12;
                break;
        }
    }
    
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    if(keytype)
    {
        UILabel *lable=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, pickerView.frame.size.width, pickerView.frame.size.height)];
        [lable setTextAlignment:NSTextAlignmentCenter];
        [lable setText:[NSString stringWithFormat:@"%d", row+3 ]];
        return lable;
    }else
    {
        if(component==0 && !view)
        {
            UILabel *date=[[UILabel alloc]initWithFrame:CGRectMake(0, 0,200, pickerView.frame.size.height)];
            date.textAlignment=NSTextAlignmentRight;
            date.text=[self dateweek:comps.day+row];
            return date;
        }
        if(component==1)
        {
            UILabel *hh=[[UILabel alloc]initWithFrame:CGRectMake(0, 0,100, pickerView.frame.size.height)];
            if(row<10)
            {
                hh.text=[NSString stringWithFormat:@"0%d",row];
            }else
            {
                 hh.text=[NSString stringWithFormat:@"%d",row];
            }
            [comps setHour:row];
            hh.textAlignment=NSTextAlignmentRight;
            return hh;
        }
       if(component==2)
       {
           UILabel *ss=[[UILabel alloc]initWithFrame:CGRectMake(0, 0,100, pickerView.frame.size.height)];
           ss.textAlignment=NSTextAlignmentCenter;
           if(row*5<10)
           {
               ss.text=[NSString stringWithFormat:@"0%d",row*5];

           }else
           {
               ss.text=[NSString stringWithFormat:@"%d",row*5];

           }
           return ss;
       }
        
    }
    return nil;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if(keytype)
    {
        return;
    }
    if(component==0)
    {
        [comps setDay:row+comps.day];
        comps = [calendar components:unitFlags fromDate:[calendar dateFromComponents:comps]];
        
        NSDateFormatter *form=[[NSDateFormatter alloc]init];
        [form setDateFormat:@"yyyy年MM月dd日"];
        date=[calendar dateFromComponents:comps];
        self.datelable.text=[form stringFromDate:date];
         comps = [calendar components:unitFlags fromDate:[NSDate date]];
        return;
    }
    if(component==1)
    {
        if(row<10)
        {
           self.timelable.text=[NSString stringWithFormat:@"0%d",row];
        }else
        {
            self.timelable.text=[NSString stringWithFormat:@"%d",row];
        }
    return;
        
    }
    if(component==2)
    {
        if(row*5<10)
        {
            self.timef.text=[NSString stringWithFormat:@"0%d",row*5];
            
        }else
        {
            self.timef.text=[NSString stringWithFormat:@"%d",row*5];
            
        }
    }
}

//返回当年几月几日
- (NSString *)dateweek:(int)day
{
    [comps setDay:day];
    comps = [calendar components:unitFlags fromDate:[calendar dateFromComponents:comps]];
    
    NSString *str=[NSString stringWithFormat:@"%d月%d日",comps.month,comps.day];
    
    str=[str stringByAppendingString:[self strweekday:comps.weekday]];
   // NSLog(@"%d**%d   %@",comps.day,comps.month,str);
    comps = [calendar components:unitFlags fromDate:[NSDate date]];
    return str;
}

//返回中文星期几
- (NSString *)strweekday:(int)week
{
    switch (week) {
        case 1:
            return @"周日";
            break;
        case 2:
            return @"周一";
            break;
        case 3:
            return @"周二";
            break;
        case 4:
            return @"周三";
            break;
        case 5:
            return @"周四";
            break;
        case 6:
            return @"周五";
            break;
        case 7:
            return @"周六";
            break;
        default:
            return @"";
            break;
    }
}
- (IBAction)close:(id)sender {
    if(keytype)
    {
        [UIView animateWithDuration:0.3 animations:^{
            [self.pickerr setFrame:CGRectMake(0, self.pickerr.frame.origin.y+self.pickerr.frame.size.height, self.pickerr.frame.size.width, self.pickerr.frame.size.height)];
        } completion:^(BOOL finished) {
            [self.pickerview removeFromSuperview];
            if([[self.segmeType titleForSegmentAtIndex:1] isEqualToString:@"聚会  (多人)"])
            {
                
                [self.segmeType setSelectedSegmentIndex:0];
            }
            
        }];

    }else
    {
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
    }
}
- (IBAction)ok:(id)sender {
   
    if(keytype)
    {
//        UILabel *lable= (UILabel *)[self.pickerr viewForRow:[self.pickerr selectedRowInComponent:0] forComponent:0];
//        rnumber=[lable.text intValue];
//        [self.segmeType setTitle:[lable.text stringByAppendingString:@"  人"] forSegmentAtIndex:1];
//        [UIView animateWithDuration:0.3 animations:^{
//            [self.pickerr setFrame:CGRectMake(0, self.pickerr.frame.origin.y+self.pickerr.frame.size.height, self.pickerr.frame.size.width, self.pickerr.frame.size.height)];
//        } completion:^(BOOL finished) {
//            [self.pickerview removeFromSuperview];
//        }];

    }else
    {
        NSDateFormatter *form=[[NSDateFormatter alloc]init];
        [form setDateFormat:@"yyyy年MM月dd日"];
        NSString *datestr=[form stringFromDate:date];
        self.datetext.text=[datestr stringByAppendingFormat:@" %@:%@",self.timelable.text,self.timef.text];
        [form setDateFormat:@"yyyy年MM月dd日 HH:mm"];
        
        okdate= [form dateFromString: [datestr stringByAppendingFormat:@" %d:%@",[self.timelable.text intValue],self.timef.text]] ;
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
    }
   
}
- (IBAction)endbut:(id)sender
{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    keytype=YES;
    self.datelable.hidden=YES;
    self.timef.hidden=YES;
    self.maohao.hidden=YES;
    self.timelable.hidden=YES;
    [self.pickerr reloadInputViews];
    [self.pickerr setFrame:CGRectMake(0, self.pickerview.frame.size.height, self.pickerr.frame.size.width, self.pickerr.frame.size.height)];
    self.endbut.hidden=NO;
    [self.view addSubview:self.pickerview];
    [self.segmeType setSelectedSegmentIndex:1];
    [UIView animateWithDuration:0.3 animations:^{
        [self.pickerr setFrame:CGRectMake(0, self.pickerr.frame.origin.y-self.pickerr.frame.size.height, self.pickerr.frame.size.width, self.pickerr.frame.size.height)];
    } completion:^(BOOL finished) {
        
    }];

}
- (IBAction)bige:(id)sender
{
    keytype=NO;
    self.datelable.hidden=NO;
    self.timef.hidden=NO;
    self.maohao.hidden=NO;
    self.timelable.hidden=NO;
    [self.picker reloadAllComponents];
    [self.picker setFrame:CGRectMake(0, self.picker.frame.origin.y, self.picker.frame.size.width, self.picker.frame.size.height)];
    [self.picker reloadInputViews];
}


@end
